<template>
	<view>
		<cover-view class="video-control">
			<!-- 加载提示信息 -->
			<cover-view class="loading-box" v-if="isLoading">
				<cover-view class="loading">{{ loadingText }}</cover-view>
			</cover-view>
			<!-- 顶控制条 -->
			<cover-view class="topbar" v-if="isShowBar">
				<cover-view class="u-f-ajc u-f-ac hd" @click="changeQuality">
					<cover-view>{{streamText}}</cover-view>
					<cover-image src="https://statics.xmcsrv.net/weixin/arrow-right.png" class="icon"></cover-image>
					<!-- <uni-icons type="bottom" color="#ffffff" style="margin-left: 10rpx;"></uni-icons> -->
				</cover-view>
				<!-- <cover-view style="display: flex; justify-content: flex-start; align-items: center">
					<cover-view class="icon" @tap.stop.prevent="onBindtapExitFullScreen" v-if="isFullScreen">
						<cover-image src="https://statics.xmcsrv.net/weixin/video-back.png" class="img"></cover-image>
					</cover-view>
				</cover-view>
				<cover-view style="display: flex; justify-content: flex-end; align-items: center">
					<cover-view class="icon" @tap.stop.prevent="onBindtapExitFullScreen" v-if="isFullScreen">
						<cover-image src="https://statics.xmcsrv.net/weixin/video-fullScreenExit.png" class="img"></cover-image>
					</cover-view>
					<cover-view class="icon" @tap.stop.prevent="onBindtapFullScreen" v-else>
						<cover-image src="https://statics.xmcsrv.net/weixin/video-fullscreen.png" class="img"></cover-image>
					</cover-view>
				</cover-view> -->
			</cover-view>
		</cover-view>
		<cover-view class="u-f-ajc u-f-c sheet" v-if="isShowHD">
			<cover-view class="u-f-ajc item" v-for="(item,index) in hdList" :key="index" @click="selectHd(item)">
				{{item.label}}</cover-view>
		</cover-view>
		<cover-view class="u-f-r bottom-control">
			<cover-view class="u-f-ajc  item">
				<!-- <cover-image :src="item" class="img" :class="{'img2':index==1}"></cover-image> -->
				<!-- <cover-image :src="iconList[0]" class="img" @click="unlockClick(index)"></cover-image> -->
				<cover-image :src="talkIcon" class="img2" @longpress="startPush" @touchend="stopPush"></cover-image>
				<!-- <cover-image :src="iconList[2]" class="img" @click="unlockClick(index)"></cover-image> -->
			</cover-view>
		</cover-view>
		<cover-view class="u-f-c right-control">
			<cover-view class="u-f-ajc  item" v-for="(item,index) in rightList" :key="index" @click="clickFunc(index)">
				<cover-image :src="item" class="img"></cover-image>
			</cover-view>
			<!-- <cover-view class="u-f-ajc  item" @click="onBindtapMuted">
				<cover-image :src="mutedIcon" class="img"></cover-image>
			</cover-view> -->
		</cover-view>
		<!-- 对讲按钮 -->
		<cover-view style="width: 10rpx;height: 10rpx;position: absolute;bottom: 120rpx;left:50%;background: transparent;transform: translateX(-50%);">
			<live-pusher id="pushLive" class="live" style="width: 1rpx;height: 1rpx;background: blue;" :url="talkUrl" mode="RTC" :autopush="isPush" :enable-camera="false" :enable-agc="true" :enable-mic="true" :enable-ans="true" @statechange="statechange2" @netstatus="netstatus" @error = "error2" audio-volume-type="voicecall" :max-bitrate="600" audio-quality="low" >
				<!-- <cover-view style="background: orange; width: 200rpx; height: 200rpx;border-radius: 100rpx;text-align: center;display: flex;justify-content: center;align-items: center;" @click="startPush">开始推送</cover-view> -->
			</live-pusher>
		</cover-view>

		<!-- 截图 -->
		<!-- <cover-image :src="captureUrl" v-if="isCapture" class="capture"></cover-image> -->
		<live-player :src="url" :min-cache="cacheMinTime" :max-cache="cacheMaxTime" autoplay mode="live"
			@statechange="statechange" :muted="isMute" @error="error" style="width: 100%" :style="{height:screenHeigh}" />
			

		<!-- 登录 -->
		<j-device-login ref="deviceLogin" :device="device" @submit="submit"></j-device-login>
		<uni-popup ref="popup" :isMaskClick="false" type="bottom">
			<view>
				<j-cell-group>
					<view class="popup-content">
						<view class="u-f-r" style="background:#FFFFFF;padding:20rpx;">
							<view class="u-f-c item" v-for="(item,index) in popupList" :key="index"
								@click="toDetail(item)">
								<cover-image :src="item.icon" class="img"></cover-image>
								<text class="desc">{{item.title}}</text>
							</view>
						</view>
					</view>
				</j-cell-group>
				<view style="padding:0 20rpx 20rpx">
					<button type="default" plain
						style="width: 100%;color: #FF0025 !important;border-color: #dcdcdc !important;background-color: #FFFFFF !important;"
						@click="closePopup">取消</button>
				</view>
			</view>
		</uni-popup>
		<!-- <j-modal title="请输入正确数字密码解锁智能门锁" v-model="show" okText="开锁" @ok="ok" @cancel="cancel" @mask="cancel">
			<uni-easyinput type="text" v-model="password" placeholder="请输入开锁密码"></uni-easyinput>
		</j-modal> -->
		<!-- 开锁弹框 -->
		<uni-popup ref="inputDialog" type="dialog" class="popupName">
			<view class="form">
				<view class="u-f-ajc title">是否打开门锁？</view>
				<!-- <view class="u-f-ajc title">请输入正确数字密码解锁智能门锁</view> -->
				<!-- <view class="form-item">
					<input :focus="focus" type="password" placeholder="请输入开锁密码" name="password" v-model="password"/>
				</view>
				<view class="desc">该密码用于远程开锁，通过手机远程，即可打开家门</view> -->
				<view class="u-f-r form-item">
					<view class="u-f-ajc cancel" @click="cancel">取消</view>
					<view class="u-f-ajc conf" @click="confimeUnlock">确认</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 设备对象
				device: {
					deviceName: ''
				},
				// 缓存列表
				deviceList: [],
				// 是否存在缓存
				isCache: false,
				//保活定时器
				timer: null,
				// 保活次数迭代变量
				keepAliveCount: 0,
				/** 推流相关 */
				// 视频对象
				videoContext: {},
				// 播放地址
				// url: 'https://img.cdn.aliyun.dcloud.net.cn/guide/uniapp/%E7%AC%AC1%E8%AE%B2%EF%BC%88uni-app%E4%BA%A7%E5%93%81%E4%BB%8B%E7%BB%8D%EF%BC%89-%20DCloud%E5%AE%98%E6%96%B9%E8%A7%86%E9%A2%91%E6%95%99%E7%A8%8B@20200317.mp4',
				url: '',
				// 高清还是标清（标清用: 1 表示， 高清用: 0 表示）
				stream: '1',
				// 高清还是标清文本说明
				streamText: '标清',
				// 高清还是标清icon
				streamTextIcon: 'FHD',
				//是否全屏
				isFullScreen: false,
				// 显示隐藏bar控条
				isShowBar: true,
				//加载中
				isLoading: true,
				//加载中文字说明
				loadingText: '正在获取视频播放地址...',
				//截图
				captureUrl: '',
				// 显示截图
				isCapture: false,
				// 时间间隔
				time: 3,
				/** 云服务 */
				isCloud: true,
				cloudText: '',
				//是否显示静音
				// isMuted: false,
				//静音
				mutedIcon:'https://statics.xmcsrv.net/weixin/soundon.png',
				isMute:false,
				talkIcon:'https://statics.xmcsrv.net/weixin/talk0.png',
				isTalk:false,
				//
				screenHeigh:'',
				isShowHD:false,
				hdText:'标清',
				hdList:[{label:'标清',id:'1'},{label:'高清',id:'0'}],
				iconList:['https://statics.xmcsrv.net/weixin/lock.png','https://statics.xmcsrv.net/weixin/talk.png','https://statics.xmcsrv.net/weixin/lock.png'],
				// rightList:['https://statics.xmcsrv.net/weixin/transfer.png','https://statics.xmcsrv.net/weixin/record.png','https://statics.xmcsrv.net/weixin/capture.png'],
				// 'https://statics.xmcsrv.net/weixin/door-cloud2.png' 设备回放
				rightList:['https://statics.xmcsrv.net/weixin/door-cloud.png','https://statics.xmcsrv.net/weixin/message.png','https://statics.xmcsrv.net/weixin/door-setting.png','https://statics.xmcsrv.net/weixin/soundon.png','https://statics.xmcsrv.net/weixin/lock1.png'],
				popupList:[
					{icon:'https://statics.xmcsrv.net/weixin/card-video.png',title:'卡存录像',url:'/jvss/pagesDevice/device/device-live/door-lock/msgDetail'},
					{icon:'https://statics.xmcsrv.net/weixin/cloud-video.png',title:'云存录像',url:'/jvss/pagesDevice/device/device-live/door-lock/msgDetail'},
					{icon:'https://statics.xmcsrv.net/weixin/album.png',title:'卡存相册',url:'/jvss/pagesDevice/device/device-live/door-lock/album'},
				],
				show: false,
				password: '',
				focus: false,
				cacheMaxTime: 1,
				cacheMinTime: 10,
				isPush:false,
				pushVideoContext:{},
				talkUrl:'',
				isLoginSuccess:true,
				isLogin:false,
			};
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function(options) {
			this.screenHeigh = uni.getSystemInfoSync().windowHeight + 'px'
			// console.log('=== device-live:onLoad:', JSON.parse(options.device));
			let enData = decodeURIComponent(options.device)
			this.device = JSON.parse(enData)
			// this.device = JSON.parse(options.device)
			// let deviceList = uni.getStorageSync('deviceList') || [];
			// deviceList.push(this.device)
			// uni.setStorageSync('deviceList', deviceList)
			this.getCurrentDevice(this.device);
			this.videoContext = uni.createVideoContext('video')
			uni.setNavigationBarTitle({
				title: this.device.deviceName
			});
			console.log('初始化时获取缓存中的设备信息：', this.device);
			this.pushVideoContext = uni.createLivePusherContext('pushLive')
			console.log('pushVideoContext=======',this.pushVideoContext);
		},
		/**
		 * 生命周期函数--监听页面初次渲染完成
		 */
		onReady: function() {
			console.log('=== device-live:onReady:');
			this.getInit();
		},
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: function() {},
		/**
		 * 生命周期函数--监听页面隐藏
		 */
		onHide: function() {
			console.log('--- device-live:onHide:');
			this.closeLivestream();
		},
		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload: function() {
			console.log('--- device-live:onUnload:');
			this.videoContext.pause();
			this.closeLivestream();
			this.pushVideoContext = null
			clearInterval(this.timer);
			this.deviceLogOut()
			uni.$emit('deviceLogout',{isBack:true,deviceNo:this.device.deviceNo})
		},
		methods: {
			
			//设备退出
			deviceLogOut(){
				let token = this.device.token
				let data = {
					Name: 'Logout',
				};
				getApp().globalData.api.deviceLogOut(data, token, (result) => {
					console.log(result,'登出')
				});
			},
			// 静音开关按钮
			onBindtapMuted(){
				this.isMute = !this.isMute
				if(this.isMute){
					this.mutedIcon = 'https://statics.xmcsrv.net/weixin/soundoff2.png'
				}else{
					this.mutedIcon = 'https://statics.xmcsrv.net/weixin/soundon.png'
				}
			},
			//开始推送
			startPush(){
				console.log('开始对讲');
				this.isPush = true
				this.talkIcon = "https://statics.xmcsrv.net/weixin/talk1.png"
				// this.isMute = true
				// this.rightList[3] = 'https://statics.xmcsrv.net/weixin/soundoff.png'
				this.pushVideoContext.start()
				uni.showToast({
					title:'开始对讲',
					icon:'none'
				})
			},
			//停止推送
			stopPush(){
				console.log('停止对讲');
				this.isPush = false
				this.talkIcon = "https://statics.xmcsrv.net/weixin/talk0.png"
				// this.isMute = false
				// this.rightList[3] = 'https://statics.xmcsrv.net/weixin/soundon.png'
				this.pushVideoContext.stop()
				uni.showToast({
					title:'对讲结束',
					icon:'none'
				})
			},
			netstatus(e) {
				console.log("netstatus:" + JSON.stringify(e));
			},
			// 播放状态变化事件
			statechange(e) {
				console.log('拉流状态===', e.detail);
				let code = e.detail.code
				if (code == 2004) {
					this.isLoading = false
				}
				if (code == 2103) {
					this.isLoading = true
					this.loadingText = '缓存中...'
					this.livestream()
				}
			},
			error(e) {
				console.error('live-player error:', e.detail.errMsg)
			},
			statechange2(e){
				console.log('推流live-pusher code:', e.detail.code)
			},
			error2(e){
			    console.error('推流live-pusher error:', e.detail.errMsg)
			} ,
			//确认开锁
			confimeUnlock() {
				uni.showLoading({
					title: '正在开锁'
				})
				let token = this.device.token;
				let data = {
					sn: this.device.deviceNo,
					props: {
						doorLock: {
							remoteUnlock: {
								password: 'zhang890'
							}
						}
					}
				};
				getApp().globalData.api.remoteUnlock(data, token, (result) => {
					uni.hideLoading();
					this.cancel()
					if (result.Ret === 100) {
						uni.showToast({
							title: '开锁成功',
						});
					} else {
						uni.showToast({
							title: '开锁失败',
							icon: 'error'
						});
					}
					// if (result.Ret === 100) {
					// 	uni.showToast({
					// 	    title: '开锁成功',
					// 		success: () => {
					// 			setTimeout(()=>{
					// 				uni.navigateBack({ })
					// 			},1000)
					// 		}
					// 	});
					// }else {
					//     uni.showToast({
					//         title: result.RetMsg
					//     });
					// }
				});
			},
			// 取消开锁
			cancel() {
				this.$refs.inputDialog.close()
			},
			//展示画质弹框
			changeQuality() {
				this.isShowHD = !this.isShowHD
			},
			//切换高清或标清
			selectHd(item) {
				this.hdText = item.label
				// this.stream = item.id
				this.isShowHD = false
				this.onBindtapSDFHD()

			},
			// 开锁
			unlockClick() {
				this.$refs.inputDialog.open()
				// uni.navigateTo({
				// 	url:'./unlock?device='+JSON.stringify(this.device)
				// })
			},
			//云回放 云事件 设置
			clickFunc(index) {
				// let urlList = ['/jvss/pagesDevice/device/device-live/replay/replay', './message', './setting/setting']
				let urlList = ['./msgDetail', './cloudMsg', './setting/setting']
				if (index == 0) {
					if (!this.isCloud) {
						uni.showToast({
							title: '暂不支持云服务',
							icon:'none'
						})
						return
					}
					if (this.cloudText == '未开通') {
						uni.showToast({
							title: '未开通云服务',
							icon:'none'
						})
						return
					}
				}
				if(index<3){
					uni.navigateTo({
						// url:'/jvss/pagesDevice/device/device-live/door-lock/setting/setting'
						url: `${urlList[index]}?device=${encodeURIComponent(JSON.stringify(this.device))}`
					})
				}else if(index == 3){
					this.isMute = !this.isMute
					if(this.isMute){
						this.rightList[3] = 'https://statics.xmcsrv.net/weixin/soundoff2.png'
					}else{
						this.rightList[3] = 'https://statics.xmcsrv.net/weixin/soundon.png'
					}
				}else if(index == 4){
					if(!this.isLogin){
						uni.showToast({
							title:'设备没有登录成功，暂不能开锁',
							icon:'none'
						})
						return
					}
					this.unlockClick()
				}
				
			},
			//卡存录像  云存录像  卡存相册
			toDetail(item) {
				uni.navigateTo({
					url: `${item.url}?device=${JSON.stringify(this.device)}`
				})
			},
			// 关闭弹框
			closePopup() {
				this.$refs.popup.close()
			},
			// 循环对比获取当前设备，否则使用传参设备
			getCurrentDevice(options) {
				let device = options//JSON.parse(options.device);
				console.log('传值数据', device);
				// let deviceList = uni.getStorageSync('deviceList') || [];
				// this.deviceList = deviceList;
				// console.log('缓存数据', deviceList);
				// let bool = false;

				// for (let i = 0; i < deviceList.length; i++) {
				// 	const item = deviceList[i];
				// 	if (item.deviceNo === device.deviceNo) {
				// 		bool = true;
				// 		this.device = item
				// 		this.deviceList = deviceList
				// 		this.isCache = true
				// 		break;
				// 	}
				// }
				// console.log(bool, 'bool')
				// if (!bool) {
				// 	this.device = device
				// 	this.deviceList.push(device);
					if (device.devPassWord) {
						this.isCache = true
					} else {
						this.isCache = false
					}
				// }
				console.log(this.isCache, 'this.isCache')
			},

			/** ======================================================== 设备播放 流程 ================================================================ */
			getInit() {
				let sns = []
				sns.push(this.device.deviceNo)
				this.getDeviceToken(sns)
			},

			// 获取设备token
			getDeviceToken(sns) {
				const data = {
					sns: sns
				};
				console.log('app:', getApp());
				getApp().globalData.api.getDeviceToken(data, (result) => {
					console.log('获取设备token:', result);
					// 遍历缓存更新当前设备的token
					this.device.token = result[0].token					
					this.deviceList.forEach((item) => {
						result.forEach((pro) => {
							if (item.deviceNo === pro.sn) {
								item.token = pro.token;
								this.device = item
							}
						});
					});
					// 根据token查询当前设置状态
					let tokenList = [];
					result.forEach((item) => {
						tokenList.push(item.token);
					});
					this.getDeviceStatus(tokenList, this.deviceList);
				});
			},
			// 获取设备状态
			getDeviceStatus(tokenList, deviceList) {
				const data = {
					token: tokenList
				};
				getApp().globalData.api.getNewDeviceStatus(data, (result) => {
					// 遍历缓存增加或更新当前设备的status
					deviceList.forEach((item) => {
						result.forEach((pro) => {
							if (item.deviceNo === pro.uuid) {
								this.$set(item, 'status', pro)
								this.device = item
							}
						});
					});
					// 遍历缓存更新BOSS中当前设备的token和status
					let bossDeviceList = uni.getStorageSync('bossDeviceList')
					bossDeviceList.forEach(item => {
						deviceList.forEach(pro => {
							if (item.deviceNo === pro.deviceNo) {
								item.token = pro.token
								item.status = pro.status
							}
						})
					})
					// 存储缓存
					uni.setStorageSync('deviceList', deviceList)
					uni.setStorageSync('bossDeviceList', bossDeviceList)
					this.getMore()
				});
			},
			// 第1步 根据传参过来的设备对象以及对象状态，做一系列的判断和准备操作
			getMore() {
				console.log('唤醒设备===================',this.device.status);
				let status = this.device.status; // 在线

				if (status.status === 'online') {
					// 低功耗设备-已休眠
					if (status.wakeUpStatus === 0) {
						// 支持远程唤醒
						if (status.wakeUpEnable === '1') {
							uni.showLoading({
								title: '唤醒设备中...'
							}); //唤醒设备

							this.wakeup(() => {
								uni.hideLoading({
									success: (res) => {
										this.loginOrAuto();
									}
								});
							});
						}
						// 不支持远程唤醒（手动唤醒）
						else {
							uni.showModal({
								title: '提示',
								content: '该设备深度休眠中，需要手动唤醒！',
								showCancel: false,
								success: (res) => {
									uni.navigateBack({
										delta: 1
									});
								}
							});
						}
					} // 低功耗设备-已唤醒
					else if (status.wakeUpStatus === 1) {
						this.loginOrAuto();
					} // 普通设备
					else {
						this.loginOrAuto();
					}
				}
			},

			// 低功耗设备唤醒
			wakeup(callback) {
				let data={
					sn:this.device.deviceNo,
					hostedControl:"1",//是否唤醒主控（空值或0：不唤醒主控；1：唤醒主控）
				}
				getApp().globalData.api.wakeup(data,this.device.token, (result) => {
					callback();
				});
			},

			// 第2步 手动登录或自动登录
			loginOrAuto() {
				this.livestream();
				this.getTalkBackUrl()
				console.log(this.isCache, 'this.isCache状态');
				if (!this.isCache && !this.device.adminToken) {
					
					console.log('token登录======1',!this.isCache && !this.device.adminToken);
					this.$refs.deviceLogin.open()
				} else {
					console.log('token登录======2',!this.isCache && !this.device.adminToken);
					this.$refs.deviceLogin.submit(this.device.devUserName, this.device.devPassWord)
				}
			},

			// 第3步 登录
			submit(options) {
				console.log(options, '登录按钮');
				// 缓存登录信息
				// if (!this.isCache) {
				// 	this.saveLoginInfo(options);
				// }
				this.isLogin = true
				this.saveLoginInfo(options);
				
				// 云服务
				this.reqCaps();
				// 保活
				this.initKeepAlive();
				
				if(!this.isLoginSuccess){
					// 直播地址
					this.livestream();
					//对讲url
					this.getTalkBackUrl()
				}
				
			},

			// 缓存登录信息
			saveLoginInfo(options) {
				let deviceList = uni.getStorageSync('deviceList') || [];
				this.device.devUserName = options.username;
				this.device.devPassWord = options.password;
				let isCache = false
				deviceList.forEach((item) => {
					if (this.device.deviceNo == item.deviceNo) {
						item.devUserName = options.username
						item.devPassWord = options.password
						isCache = true
					}
				})
				if (!isCache) {
					deviceList.push(this.device);
				}
				uni.setStorageSync('deviceList', deviceList);
			},

			// 第4步-1 保活
			// 20秒执行一次，当连续请求两次保活失败时，则不再保活
			initKeepAlive() {
				console.log('定时器：', this.timer);

				if (this.timer !== null) {
					clearInterval(this.timer);
					this.timer = null
				}

				this.timer = setInterval(() => {
					this.keepAlive();
				}, 20000)
			},

			// 保活
			keepAlive() {
				let token = this.device.token;
				getApp().globalData.api.keepAlive(token, (result) => {
					// console.log('保活：', result);

					if (result.data.code === 2000) {
						if (result.data.data.Ret === 100) {
							// 不需要操作
						} else {
							if (this.keepAliveCount === 0) {
								this.keepAliveCount = this.keepAliveCount + 1
								this.initKeepAlive();
							} else {
								clearInterval(this.timer);
							}
						}
					} else {
						if (this.keepAliveCount === 0) {
							this.keepAliveCount = this.keepAliveCount + 1
							this.initKeepAlive();
						} else {
							clearInterval(this.timer);
						}
					}
				});
			},

			// 第4步-2 获取设备直播地址
			livestream() {
				let token = this.device.token;
				let data = {
					mediaType: 'rtmp',
					channel: '0',
					stream: this.stream,
					protocol: 'ts',
					username: this.device.devUserName,
					devPwd: this.device.devPassWord,
					userToken: uni.getStorageSync('accessToken'),
					appKey: getApp().globalData.api.appKey,
					encryptType:'DISABLE',
				};
				let constant = getApp().globalData.constant;
				if(this.device.pid === constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK5 || this.device.pid === constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK6 || this.device.pid === constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK7){
					data.videoCode = 'h264'  //乐鑫屏显智能云锁
				}
				if(this.device.adminToken){
					data.authentication = this.device.adminToken
					data.encryptType = 'TOKEN'
				}
				console.log('实时视频获取');
				getApp().globalData.api.livestream(data, token, (result) => {
					console.log('获取设备直播地址:', result); // 渲染层网络层错误

					if (result && (result.Ret === 100 || result.Ret === 104)) {
						// let url = result.url;
						// this.keepRequestUntillRight(url);
						this.url = result.url
						this.isLoginSuccess = true
					}
					//用户名密码错误
					else if(result.Ret == 106){
						this.isLoginSuccess = false
						this.$refs.deviceLogin.open()
					}
					// 其他错误情况
					else {
						uni.showModal({
							title: '提示',
							content: getApp().globalData.errCodeMsg.RetCodeMsg[result.Ret] || result
								.retMsg,
							showCancel: false
						});
					}
				});
			},
			// 获取对讲地址
			getTalkBackUrl(){
				let token = this.device.token;
				let data = {
					mediaType: 'rtmp',
					channel: '0',
					audioCode: 'acc',
					username: this.device.devUserName,
					password: this.device.devPassWord,
					userToken: uni.getStorageSync('accessToken'),
					appKey: getApp().globalData.api.appKey,
					// forceIp:'122.9.143.195',
					encryptType:'DISABLE',
				};
				if(this.device.adminToken){
					data.authentication = this.device.adminToken
					data.encryptType = 'TOKEN'
				}
				getApp().globalData.api.talkbackUrl(data, token, (result) => {
					console.log('获取设备对讲地址:', result); // 渲染层网络层错误
					if (result && (result.Ret === 100 || result.Ret === 104)) {
						// let url = result.url;
						// this.keepRequestUntillRight(url);
						this.talkUrl = result.url
					}
					// 其他错误情况
					else {
						uni.showModal({
							title: '提示',
							content: getApp().globalData.errCodeMsg.RetCodeMsg[result.Ret] || result
								.retMsg,
							showCancel: false
						});
					}
				});
			},

			// 停止设备码流
			closeLivestream(callback) {
				const token = this.device.token;
				const data = {
					channel: '0',
					stream: this.stream,
					PassWord:this.device.devPassWord,
					UserName:this.device.devUserName,
					EncryptType:'DISABLE',
					Authentication:this.device.token
				};
				getApp().globalData.api.closeLivestream(data, token, (result) => {
					console.log('停止设备码流:', result);

					if (typeof callback === 'function') {
						callback();
					}
				});
			},

			// 一直请求直到请求成功（处理：渲染层网络层错误）
			keepRequestUntillRight(url) {
				console.log('=====一直请求直到请求成功=======');
				uni.request({
					method: 'GET',
					url,
					success: (res) => {
						if (res.statusCode == 200) {
							this.url = url
							this.isLoading = false
						} else if (res.statusCode == 400) {
							uni.showModal({
								title: '提示',
								content: res.data,
								showCancel: false
							});
						} else {
							setTimeout(() => {
								this.keepRequestUntillRight(url);
							}, 1000);
						}
					},
					fail: (err) => {
						console.log('error:', err);
					}
				});
			},
			//获取云服务状态
			reqCaps() {
				const data = {
					sn: this.device.deviceNo,
					caps: ['xmc.css']
				};
				getApp().globalData.api.reqCaps(data, (result) => {
					console.log('云服务:', result);
					let time = Math.floor(new Date().getTime() / 1000);
					let caps = result.caps;
					let text = '';
					let flag = false;

					if (!caps['xmc.css.vid.support']) {
						// 不支持的情况下不要显示出来
						text = '不支持';
						flag = false;
					} else if (!caps['xmc.css.vid.enable']) {
						text = '未开通';
						flag = true;
					} else if (caps['xmc.css.vid.expirationtime'] < time) {
						text = '已过期';
						flag = true;
					} else {
						text = '';
						flag = true;
					}
					this.isCloud = flag
					this.cloudText = text
					console.log(this.isCloud);
				});
			},
			/** ======================================================== video回调 ================================================================== */
			// 显示隐藏控条bar
			bindtap() {
				console.log('binftap');
				this.isShowBar = !this.isShowBar
				if (!this.isShowBar) {
					this.isShowHD = false
				}

			},

			// 当开始/继续播放时触发play事件
			bindplay(ev) {
				console.log('当开始/继续播放时触发play事件:', ev);
			},

			// 当暂停播放时触发 pause 事件
			bindpause(ev) {
				console.log('当暂停播放时触发 pause 事件:', ev);
			},

			// 当播放到末尾时触发 ended 事件
			bindended(ev) {
				console.log('当暂停播放时触发 pause 事件:', ev);
			},

			// 播放进度变化时触发
			bindtimeupdate(ev) {
				// console.log('播放进度变化时触发:',ev);
				if (this.isLoading) {
					this.isLoading = false
				}
			},

			// 视频进入和退出全屏时触发
			bindfullscreenchange(ev) {
				console.log('视频进入和退出全屏时触发:', ev);
			},

			// 视频出现缓冲时触发
			bindwaiting(ev) {
				console.log('视频出现缓冲时触发:', ev);
				this.isLoading = true
				this.loadingText = '缓冲中...'
			},

			// 视频播放出错时触发
			binderror(ev) {
				console.log('视频播放出错时触发:', ev);
				uni.showModal({
					title: '提示',
					content: '媒体链接已断开,请重试',
					showCancel: false,
					success: (res) => {
						if (res.confirm) {
							let tokenList = [this.device.token];
							this.getDeviceStatus(tokenList, this.deviceList)
						}
					}

				});
			},

			// 加载进度变化时触发，只支持一段加载
			bindprogress(ev) {
				// console.log('加载进度变化时触发，只支持一段加载:', ev);
			},

			// 视频元数据加载完成时触发
			bindloadedmetadata(ev) {
				console.log('视频元数据加载完成时触发:', ev);
			},

			// 切换 controls 显示隐藏时触发
			bindcontrolstoggle(ev) {
				console.log('切换 controls 显示隐藏时触发:', ev);
			},

			// 播放器进入小窗
			bindenterpictureinpicture(ev) {
				console.log('播放器进入小窗:', ev);
			},

			// 播放器进入小窗
			bindleavepictureinpicture(ev) {
				console.log('播放器退出小窗:', ev);
			},

			// seek 完成时触发
			bindseekcomplete(ev) {
				console.log('seek 完成时触发:', ev);
			},

			/** ================================================== 标高清切换 & 截图 =================================================================== */
			// 标清高清切换
			onBindtapSDFHD() {
				if (this.stream === '0') {
					this.isLoading = true
					this.loadingText = '切换为标清...'
					this.url = ''
					this.streamText = '标清'
					this.streamTextIcon = 'SD'
				} else {
					this.isLoading = true
					this.loadingText = '切换为高清...'
					this.url = ''
					this.streamText = '高清'
					this.streamTextIcon = 'FHD'
				}

				this.closeLivestream(() => {
					if (this.stream === '0') {
						this.stream = '1'
					} else {
						this.stream = '0'
					}

					setTimeout(() => {
						this.livestream();
					}, 3000);
				});
			},

			/**===================================================== 其他 ============================================================================= */
			// 全屏
			onBindtapFullScreen(ev) {
				console.log('全屏：', ev);
				this.videoContext.requestFullScreen();
				this.isFullScreen = true
			},

			// 取消全屏
			onBindtapExitFullScreen(ev) {
				console.log('取消全屏：', ev);
				this.videoContext.exitFullScreen();
				this.isFullScreen = false
			},

			// 云服务
			onBindtapCloud() {
				uni.navigateTo({
					url: `/jvss/pagesDevice/device/device-live/cloud/cloud?device=${JSON.stringify(this.device)}`
				});
			},

			// 云回放
			onBindtapReplay() {
				uni.navigateTo({
					url: `/jvss/pagesDevice/device/device-live/replay/replay?device=${JSON.stringify(this.device)}`
				});
			},

			// 设置
			onBindtapSetting() {
				uni.navigateTo({
					url: `/jvss/pagesDevice/device/device-live/setting/setting?device=${JSON.stringify(this.device)}`
				});
			}
		}
	};
</script>
<style lang="scss">

    .popupName {
        /deep/ .uni-popup__wrapper {
            top: -100rpx;
        }
    }
	page {
		overflow: hidden;
	}

	.video-control {
		width: 100%;
		height: 100rpx;
		line-height: 100rpx;
		position: absolute;
		top: 0;
		left: 0;
		z-index: 99;
	}

	.loading-box {
		width: 100%;
		height: 100%;
		position: absolute;
		left: 0;
		top: 0;
		z-index: 99;
		color: #ffffff;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.hd {
		position: absolute;
		right: 50rpx;
		top: 20rpx;
		z-index: 110;
		color: #ffffff;
		font-size: 26rpx;
		width: 140rpx;
		height: 50rpx;
		background: rgba(0, 0, 0, 0.39);
		border-radius: 25rpx;
	}

	.sheet {
		z-index: 99;
		position: absolute;
		width: 150rpx;
		top: 90rpx;
		right: 40rpx;
		background: white;
		padding: 0rpx 30rpx 30rpx;
		border-radius: 16rpx;

		
		.item {
			margin-top: 30rpx;
		}
	}

	.bottom-control {
		z-index: 999;
		position: absolute;
		height: 230rpx;
		bottom: 120rpx;
		right: 30rpx;
		left: 30rpx;

		.item {
			flex: 1;

			.img {
				width: 96rpx;
				height: 96rpx;
				margin: 0 40rpx;
			}

			.img2 {
				width: 210rpx;
				height: 210rpx;
			}
		}

	}

	.right-control {
		z-index: 99;
		position: absolute;
		height: 400rpx;
		right: 30rpx;
		top: 50%;
		transform: translateY(-50%);

		.item {
			flex: 1;

			.img {
				width: 70rpx;
				height: 70rpx;
			}

		}
	}

	/deep/.uni-popup {
		z-index: 115;
	}

	.form {
		background: white;
		padding: 60rpx;
		border-radius: 10rpx;

		.title {
			font-size: 34rpx;
			font-weight: bold;
			line-height: 49rpx;
			color: #464646;
		}

		.desc {
			font-size: 22rpx;
			color: #8A8A8A;
			line-height: 84rpx;
		}

		.form-item {
			margin-top: 40rpx;

			input {
				border: 1rpx solid #A5A5A5;
				border-radius: 8rpx;
				padding: 10rpx;
			}

			.cancel {
				background: #F6F7FB;
				color: #000000;
				font-size: 30rpx;
				width: 237rpx;
				height: 84rpx;
				border-radius: 42rpx;
			}

			.conf {
				margin-left: 20rpx;
				background: #FF0025;
				color: #ffffff;
				font-size: 30rpx;
				width: 237rpx;
				height: 84rpx;
				border-radius: 42rpx;
			}
		}
	}

	.loading {
		width: 100%;
		height: 72rpx;
		line-height: 72rpx;
		text-align: center;
		color: #ffffff;
	}

	.topbar {
		width: 100%;
		position: absolute;
		left: 0;
		top: 0;
		z-index: 100;
		color: #ffffff;
		/* background: linear-gradient(rgba(0,0,0,1), rgba(0,0,0,0)); */
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 90rpx;

		.icon {
			transform: rotate(90deg);
			width: 36rpx;
			height: 36rpx;
		}
	}

	/* .bottombar {
    width: 100%;
    position: absolute;
    left: 0;
    bottom: 7rpx;
    z-index: 100;
    color: #FFFFFF;
    background: linear-gradient(rgba(0,0,0,0), rgba(0,0,0,1));
    background: rgba(0,0,0,0.5);
    display: flex;
    justify-content: flex-end;
    align-items: center;
} */

	.icon {
		width: 72rpx;
		height: 72rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.img {
		display: block;
		width: 36rpx;
		height: 36rpx;
	}

	.capture {
		position: absolute;
		top: 30rpx;
		left: 0;
		right: 0;
		z-index: 999;
		width: 80%;
		height: auto;
		border: 1px solid red;
		box-shadow: 0rpx 10rpx 30rpx rgba(0, 0, 0, 0.75);
		margin: auto;
	}

	.jf-button {
		background: transparent;
		width: auto;
		margin: 0;
		line-height: 1.25;
	}

	.jf-button::after {
		border: none;
	}

	.video-control-extra {
		height: 10vh;
		display: flex;
		justify-content: space-between;
		align-items: center;
		background: #ffffff;
	}

	.control-inner {
		position: relative;
		display: flex;
		justify-content: center;
		align-items: center;
		width: 35vw;
		height: 35vw;
		border-radius: 100%;
		border: 1px solid #cccccc;
	}

	.control-handle {
		display: block;
		width: 48rpx;
		height: 48rpx;
		position: absolute;
	}

	.control-top {
		top: 0;
	}

	.control-top-right {
		top: 30rpx;
		right: 30rpx;
		transform: rotate(45deg);
	}

	.control-right {
		right: 0;
		transform: rotate(90deg);
	}

	.control-right-bottom {
		right: 30rpx;
		bottom: 30rpx;
		transform: rotate(135deg);
	}

	.control-bottom {
		bottom: 0;
		transform: rotate(180deg);
	}

	.control-bottom-left {
		bottom: 30rpx;
		left: 30rpx;
		transform: rotate(225deg);
	}

	.control-left {
		left: 0;
		transform: rotate(270deg);
	}

	.control-left-top {
		left: 30rpx;
		top: 30rpx;
		transform: rotate(315deg);
	}

	.control-center {
		width: 12vw;
		height: 12vw;
		border-radius: 100%;
		background: #FF0025;
	}

	.box {
		width: 100rpx;
		height: 100rpx;
		border: 1px solid #999999;
		border-radius: 12rpx;
		line-height: 100rpx;
		text-align: center;
		font-size: 36rpx;
	}

	.box.active {
		border: 1px solid #FF0025;
		color: #FF0025;
	}

	.cruise-empty {
		width: 100vw;
		height: 50vh;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #999999;
		text-align: center;
		font-size: 24rpx;
		background: #FFFFFF;
	}

	.popup-content {
		.item {
			padding: 40rpx 0;
			flex: 1;
			justify-content: center;
			display: flex;
			align-items: center;

			.desc {
				color: #666666;
				font-size: 30rpx;
				margin-top: 10rpx;
			}

			.img {
				width: 120rpx;
				height: 120rpx;
			}

		}

		.confirm {
			font-size: 30rpx;
			color: #2CBDB8;
			height: 98rpx;
		}

		.btn {
			width: 100%;
			color: #FF0025 !important;
			border-color: #dcdcdc !important;
			background-color: #FFFFFF !important;
		}
	}
</style>
